package cn.cyber.wxfire.controller;

import cn.cyber.wxfire.pojo.Student;
import cn.cyber.wxfire.pojo.Teacher;
import cn.cyber.wxfire.service.StudentServer;
import cn.cyber.wxfire.service.TeacherServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@Controller
public class LoginController {
    @Autowired
    private StudentServer studentServer;
    @Autowired
    private TeacherServer teacherServer;

    @RequestMapping("/user/login")
    public String login(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            Model model, HttpSession session, HttpServletResponse response) {

        Student student=new Student();
        student.setPassword(password);
        student.setNum(username);
        System.out.println(student);


        List<Student> studentsList=studentServer.loginStudent(student);

       if(!studentsList.isEmpty())
       {
           //登陆成功后给与一个session
           session.setAttribute("loginUser",username);
           session.setAttribute("identity","student");
           //重定向
           return "redirect:../personCenter";
       }
       else
       {
           Teacher teacher=new Teacher();
           teacher.setPassword(password);
           teacher.setNum(username);
           System.out.println(teacher);
           List<Teacher> teachersList=teacherServer.loginTeacher(teacher);
           if(!teachersList.isEmpty()){
               session.setAttribute("loginUser",username);
               session.setAttribute("identity","teacher");
               return "redirect:../personCenter";
           }
           else{
               response.setCharacterEncoding("GBK");
               System.out.println("222");
               PrintWriter out = null;
               try {
                   out = response.getWriter();
               } catch (IOException e) {
                   e.printStackTrace();
               }
               out.print("<script>alert('密码或用户名错误'); window.location.href='http://localhost/'</script>");
               out.flush();
               out.close();


               return "signIn";
           }

       }
    }
}
